<script setup>
import { ref,watch,onMounted } from 'vue';
import axios from 'axios'
import { queryPublic,getProv,getCityByProv } from '@/api/PublicSupervision'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router';

const router = useRouter();

// 查询信息处理函数
const handleViewInfo = (row) => {
  const id = row.id;
  localStorage.setItem('publicSupervisionId', id);
  router.push({ name: 'PublicSupervisionDetail' });
};

// 指派处理函数
const handleAssign = (row) => {
  const id2 = row.id;
  localStorage.setItem('GridWorkerAssignmentId', id2);
  router.push({ name: 'GridWorkerAssignment' });
};
//搜索表单对象
const searchForm = ref({
  gridProvince: '',
  gridCity: '',
  estimatedAqiLevel: '',
  status: '',
  date: [],
  begin: '',
  end: ''
})


//省份列表
const provinceList = ref([])
//获取省份列表
const getProvinceList = async () => { 
  const result = await getProv();
  provinceList.value = result.data;
}

// 城市列表
const cityList = ref([])

// 获取城市列表
const getCityList = async (province) => {
  if (!province) {
    cityList.value = [];
    return;
  }
  try {
    console.log(province);
    const result = await getCityByProv(province);
    if (result.code === 200) {
      cityList.value = result.data;
    } else {
      ElMessage.error('获取城市列表失败');
      cityList.value = [];
    }
  } catch (error) {
    console.error('获取城市列表失败', error);
    ElMessage.error('网络异常，请稍后再试');
    cityList.value = [];
  }
}
// 监听省份选择变化
watch(
  () => searchForm.value.gridProvince,
  (newProvince) => {
    getCityList(newProvince); // 根据新省份获取城市列表
  }
);

//侦听searchForm的date属性
watch(() => searchForm.value.date, (newVal) => { 
  if(newVal.length == 2){
    searchForm.value.begin = newVal[0];
    searchForm.value.end = newVal[1];
  }else{
    searchForm.value.begin = '';
    searchForm.value.end = '';
  }
})
//查询列表数据
const search = async () => { 
  if(searchForm.value.status === ''){
    const queryData = {
    gridProvince: searchForm.value.gridProvince,
    gridCity: searchForm.value.gridCity,
    estimatedAqiLevel: searchForm.value.estimatedAqiLevel,
    begin: searchForm.value.begin,
    end: searchForm.value.end,
    page: currentPage.value , // 注意接口中page一般从0开始，这里假设currentPage从1开始，需减1
    pageSize: pageSize.value
    }
      const result = await queryPublic(queryData);
    publicList.value = result.data.data;
    total.value = result.data.total;
  }else{
    const queryData = {
    gridProvince: searchForm.value.gridProvince,
    gridCity: searchForm.value.gridCity,
    estimatedAqiLevel: searchForm.value.estimatedAqiLevel,
    status: searchForm.value.status,
    begin: searchForm.value.begin,
    end: searchForm.value.end,
    page: currentPage.value , // 注意接口中page一般从0开始，这里假设currentPage从1开始，需减1
    pageSize: pageSize.value
  };
    const result = await queryPublic(queryData);
  
  publicList.value = result.data.data;
  total.value = result.data.total;
  }
  

  // const result = await queryPublic(searchForm.value.gridProvince,
  //                                   searchForm.value.gridCity,
  //                                   searchForm.value.estimatedAqiLevel,
  //                                   searchForm.value.begin,
  //                                   searchForm.value.end,
  //                                   currentPage.value,
  //                                   pageSize.value);
}
//清空
const clear = () => { 
  searchForm.value = { gridProvince: '', gridCity: '', estimatedAqiLevel: '', status: '', date: [], begin: '', end: '' };
  search();
}
//列表数据
const publicList = ref([])

//分页
const currentPage = ref(1)
const pageSize = ref(10)
const background = ref(true)
const total = ref(0)

const handleSizeChange = (val) => {
  search();
}
const handleCurrentChange = (val) => {
  search();
}




onMounted(() => { 
  search();
  getProvinceList();
})
</script>

<template>
  <!-- 标题 -->
  <!-- <div class="container">
    <h1>公众监督数据管理&nbsp; / &nbsp; 公众监督数据列表</h1>
  </div> -->
  <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>公众监督数据管理</el-breadcrumb-item>
      <el-breadcrumb-item>公众监督数据列表</el-breadcrumb-item>
    </el-breadcrumb>

  <!-- 搜索栏 -->
  <div class="container">
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
    <!-- 省区域 -->
    <el-form-item label="省区域">
      <el-select v-model="searchForm.gridProvince" placeholder="--全部--">
        <el-option v-for="p in provinceList"  :label="p" :value="p"></el-option>
      </el-select>
    </el-form-item>
    <!-- 市区域 -->
    <el-form-item label="市区域">
      <el-select v-model="searchForm.gridCity" placeholder="--全部--">
        <el-option v-for="c in cityList"  :label="c" :value="c"></el-option>
      </el-select>
    </el-form-item>
    <!-- 预估等级 -->
    <el-form-item label="预估等级">
      <el-select v-model="searchForm.estimatedAqiLevel" placeholder="--全部--">
        <el-option label="优（一）" value="1" />
        <el-option label="良（二）" value="2" />
        <el-option label="轻度污染（三）" value="3" />
        <el-option label="中度污染（四）" value="4" />
        <el-option label="重度污染（五）" value="5" />
        <el-option label="严重污染（六）" value="6" />
      </el-select>
    </el-form-item>
    <!-- 指派情况 -->
    <el-form-item label="指派情况">
      <el-select v-model="searchForm.status" placeholder="--全部--">
        <el-option label="待指派" value="PENDING" />
        <el-option label="处理中" value="PROCESSING" />
        <el-option label="已完成" value="COMPLETED" />
      </el-select>
    </el-form-item>
    <!-- 反馈日期 -->
    <el-form-item label="反馈日期">
      <el-date-picker
        v-model="searchForm.date"
        type="daterange"
        range-separator="到"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <!-- 查询按钮 -->
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="danger" @click="clear">清空</el-button>
    </el-form-item>
  </el-form>
  </div>

  <!-- 表格 -->
  <div class="container">
    <el-table :data="publicList" border style="width: 100%">
      <el-table-column prop="id" label="编号" width="100" align="center"/>
      <el-table-column prop="supervisorName" label="反馈者姓名" width="180" align="center"/>
      <el-table-column prop="gridProvince" label="所在省" width="180" align="center"/>
      <el-table-column prop="gridCity" label="所在市" width="180" align="center"/>
      <el-table-column prop="estimatedAqiLevel" label="预估污染等级" width="180" align="center"/>
      <el-table-column prop="feedbackTime" label="反馈时间" width="260" align="center"/>
      <el-table-column label="操作" align="center">
        <!-- <el-button type="primary" @click="">查询信息</el-button>
        <el-button type="danger" @click="">指派</el-button> -->
        <template #default="scope">
          <div v-if="scope.row.status === 'PENDING'">
            <el-button type="text" size="small" @click="handleViewInfo(scope.row)">
              <el-icon class="icon-large"><Document /></el-icon>
            </el-button>
            <el-button type="text" size="small" @click="handleAssign(scope.row)">
              <el-icon class="icon-large"><Position /></el-icon>
            </el-button>
          </div>
          <div v-else>
            <el-button type="text" size="small" @click="handleViewInfo(scope.row)">
              <el-icon class="icon-large"><Document /></el-icon>
            </el-button>
            <el-button disabled="true" type="text" size="small" @click="handleAssign(scope.row)">
              <el-icon class="icon-large"><Position /></el-icon>
            </el-button>
          </div>

           
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页条 -->
   <div class="container">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
   </div>
</template>

<style scoped>
.icon-large {
  font-size: 18px; /* 调整为你需要的大小 */
}
.container{
  margin: 15px 0px ;
}
.demo-form-inline {
  display: flex;
  align-items: center;
  flex-wrap: nowrap; /* 强制不换行 */
  gap: 10px; /* 表单项之间的间距 */
}

.el-form-item {
  white-space: nowrap;
  flex-shrink: 0; /* 防止被压缩 */
}

.el-form-item__content {
  width: auto;
}

/* 如果需要对某些项单独设置宽度，也可以在这里统一定义 */
.demo-form-inline .el-form-item:nth-child(1),
.demo-form-inline .el-form-item:nth-child(2),
.demo-form-inline .el-form-item:nth-child(3),
.demo-form-inline .el-form-item:nth-child(4) {
  width: 150px;
}

.demo-form-inline .el-form-item:nth-child(5) {
  width: 350px;
}

/* 让按钮在同一行显示 */
.demo-form-inline .el-form-item:last-child {
  display: flex;
  gap: 10px;
}
</style>
